package org.nanotek.tika.job.writer;

import java.util.List;
import java.util.Queue;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.nanotek.Base;
import org.nanotek.tika.MediaDetail;
import org.nanotek.tika.io.TikaMediaDetector;
import org.springframework.batch.item.ItemWriter;

public class QueueBaseWriter implements ItemWriter<Queue<Base<?>>> {

	private TikaMediaDetailDetector<?,Base<String>> tikaMediaDetector; 
	private MediaDetailBaseTemplate mediaDetailBaseTemplate;
	private IndexWriter indexWriter; 
	
	@SuppressWarnings("unchecked")
	@Override
	public void write(List<? extends Queue<Base<?>>> items) throws Exception {
		Queue<Base<?>> queueBase = items.get(0);
		Base<String> element;
		if (queueBase !=null)
		{ 
			while ((element = (Base<String>) queueBase.poll())!=null)
			{ 
				System.out.println(element.getId());
				MediaDetail detail = tikaMediaDetector.detect(element);
				if (detail ==null)
					System.err.println("NO MEDIA DETAIL FOUND ON FILE ++++++" + element.getId() + " ++++++ ");
				else 
					System.out.println(detail.toString());
				Document document = mediaDetailBaseTemplate.createTemplate(detail);
				if (document !=null && document.getFields().size() > 0)
					indexWriter.addDocument(document);	
			}
		}
	}

	public TikaMediaDetailDetector getTikaMediaDetector() {
		return tikaMediaDetector;
	}

	public void setTikaMediaDetector(TikaMediaDetailDetector tikaMediaDetector) {
		this.tikaMediaDetector = tikaMediaDetector;
	}

	public MediaDetailBaseTemplate getMediaDetailBaseTemplate() {
		return mediaDetailBaseTemplate;
	}

	public void setMediaDetailBaseTemplate(
			MediaDetailBaseTemplate mediaDetailBaseTemplate) {
		this.mediaDetailBaseTemplate = mediaDetailBaseTemplate;
	}

	public IndexWriter getIndexWriter() {
		return indexWriter;
	}

	public void setIndexWriter(IndexWriter indexWriter) {
		this.indexWriter = indexWriter;
	}
}
